import axios from 'axios'
import Cookies from 'js-cookie'
import * as types from '../mutation-types'

// state
export const state = {
    user: null,
    token: Cookies.get('UserTicket'),
    address: {
        lng: 0,
        lat: 0
    },
    defaultCar: null,
    isApp: navigator.userAgent.includes('yangche51')
}

// getters
export const getters = {
    user: state => state.user,
    token: state => state.token,
    check: state => state.user !== null,
    address: state => state.address,
    defaultCar: state => state.defaultCar,
    isApp: state => state.isApp,
}

// mutations
export const mutations = {
    [types.SAVE_TOKEN](state, {token, remember}) {
        state.token = token
        Cookies.set('UserTicket', token, {expires: remember ? 365 : null})
    },

    [types.FETCH_USER_SUCCESS](state, {user}) {
        state.user = user
    },

    [types.FETCH_USER_FAILURE](state) {
        state.token = null
        Cookies.remove('UserTicket')
    },

    [types.LOGOUT](state) {
        state.user = null
        state.token = null
        Cookies.remove('UserTicket')
    },

    [types.UPDATE_USER](state, {user}) {
        state.user = user
    },
    getAddress(state,data){
        state.address = data
    },
    getDefaultCar(state,data){
        state.defaultCar = data
    }
}

// actions
export const actions = {
    saveToken({commit, dispatch}, payload) {
        commit(types.SAVE_TOKEN, payload)
    },

    async fetchUser({commit}) {
        try {

            const {data} = await axios.post('customer/UserInfo/MyManager',{})
            commit(types.FETCH_USER_SUCCESS, {user: data.Body.myUserInfo})
        } catch (e) {

            commit(types.FETCH_USER_FAILURE)
            throw  e;
        }
    },

    updateUser({commit}, payload) {
        commit(types.UPDATE_USER, payload)
    },

    async logout({commit}) {
        try {
            await axios.post('logout')
        } catch (e) {
        }

        commit(types.LOGOUT)
    },

    async getDefaultCar({state,commit, dispatch}, payload){
        let value = {}
        console.log(state)
        // let 
        if(state.isApp){
            try{
                value = JSON.parse(window.yangcheJS.getCar())
            }catch(e){
                console.log(e)
            }
        }else if (localStorage.getItem('YC51_Web_Auto')) {
            value = JSON.parse(localStorage.getItem('YC51_Web_Auto'))
        } else {
            let res =  await axios.get("//app.yangche51.com/6_1/car/syncar_1_0.ashx")
            if(!res.data.body){
                return;
            }
            let data = res.data.body.autoModel
            let arr = []
            data.carParams.forEach((v, k) => {
                arr[k] = {}
                arr[k].k = v.paramTypeId
                arr[k].v = v.paramValueId
                arr[k].kn = v.paramTypeName
                arr[k].vn = v.paramValue
            })
            data.carParams = arr
            value = {
                ap: data.carParams,//车型参数信息
                i: "",//车型图片
                m: 0,//车型月份
                mi: data.mileage,//当前行驶里程
                n: data.carName,//车型显示名称
                rt: data.startYearMonth,//上路时间
                s: data.autoModelSubId,//车型排量编号
                sync: true,
                y: data.year,//车型年份
                autoPic: data.autoPic,
                AutoBrandName: data.AutoBrandName,
                MAutoModelName: data.MAutoModelName,
                AutoModelName: data.AutoModelName
            }
            localStorage.setItem('YC51_Web_Auto', JSON.stringify(value));
        }
        commit("getDefaultCar",value)
    }
}
